package com.scau.hwadee.examination.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Locale;
import java.util.Map;


/**
 * @author: YHX
 * @Date: 2019/7/4 14:08
 * 邮件发送工具类
 */
@Slf4j
public class SendEmailUtils implements Runnable {
  private JavaMailSender javaMailSender;
  private TemplateEngine templateEngine;
  private Map<String, Object> map;

  public SendEmailUtils(JavaMailSender javaMailSender, TemplateEngine templateEngine, Map<String, Object> map) {
    this.javaMailSender = javaMailSender;
    this.templateEngine = templateEngine;
    this.map = map;
  }

  @Override
  public void run() {
    try {
      MimeMessage message = javaMailSender.createMimeMessage();
      MimeMessageHelper helper = new MimeMessageHelper(message, true);
      helper.setTo(map.get("userEmail").toString());
      helper.setFrom("1769969562@qq.com");
      Context ctx = new Context(Locale.getDefault(), map);
      String mail = templateEngine.process(map.get("html").toString(), ctx);
      helper.setText(mail, true);
      javaMailSender.send(message);
      log.debug("邮件发送成功");
    } catch (MessagingException e) {
      log.debug("邮件发送失败，错误为：", e);
    }
  }
}
